package com.android.tcc;

import android.graphics.Canvas;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import hypermedia.video.OpenCV;

/**
 * A CameraSource implementation that obtains its bitmaps directly from the
 * device camera.
 * 
 * @author David Machado
 *
 */

public class GenuineCamera implements CameraSource {

	private final int width;
	private final int height;
	
	OpenCV opencv;
	Camera camera;
	
	public GenuineCamera(int width, int height) {
		this.width = width;
		this.height = height;
	}
	
	@Override
	public int getWidth() {
		return width;
	}
	
	@Override
	public int getHeight() {
		return height;
	}
	
	@Override
	public boolean open() {
		if (camera != null) return true;
		camera = Camera.open();
		if (camera == null) return false;
		
		//parameters for the device mostly as specified in sample app
		//Camera param = new Camera.Size(1280, 960);
		Camera.Parameters param;
		/*param.type = 1; // preview
		param.srcWidth = 1280;
		param.srcHeight = 960;
		param.leftPixel = 0;
		param.topPixel = 0;
		param.outputWidth = width;
		param.outputHeight = height;
		param.dataFormat = 2; // RGB_565 */ 
	
		//attempt to configure the device here
		//if (!camera.setCaptureParams(param)) {
		if (!camera.setParameters(param))
			camera.close();
			camera = null;
			return false;
		}
		
		return true;
	}
	
	@Override
	public void close() {
		if (camera == null) return;
		camera.close();
		camera = null;
	}
	
	@Override
	public boolean capture(Canvas canvas) {
		if (camera == null) return false;
		return camera.capture(canvas);
	}
	
	void setup() {

	    size( 320, 240 );

	    opencv = new OpenCV(this);
	    opencv.capture( width, height );
	    opencv.cascade( OpenCV.CASCADE_FRONTALFACE_ALT );    // load the FRONTALFACE description file
	}

	void draw() {
	    
	    opencv.read();
	    image( opencv.image(), 0, 0 );
	    
	    // detect anything ressembling a FRONTALFACE
	    Rectangle[] faces = opencv.detect();
	    
	    // draw detected face area(s)
	    noFill();
	    stroke(255,0,0);
	    for( int i=0; i<faces.length; i++ ) {
	        rect( faces[i].x, faces[i].y, faces[i].width, faces[i].height ); 
	    }
	} 

}